<template>
  <div class="cost-analysis-page">
    <!-- 分析概览卡片 -->
    <el-row :gutter="20" class="overview-cards">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon current-cost">
              <el-icon size="24"><TrendCharts /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">¥{{ formatNumber(analysisOverview.currentMonthCost) }}</div>
              <div class="card-label">本月成本</div>
              <div class="card-trend up">
                <el-icon><Top /></el-icon>
                {{ analysisOverview.monthGrowth }}%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon cost-rate">
              <el-icon size="24"><DataAnalysis /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">{{ analysisOverview.costRate }}%</div>
              <div class="card-label">成本率</div>
              <div class="card-trend down">
                <el-icon><Bottom /></el-icon>
                {{ analysisOverview.rateChange }}%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon cost-save">
              <el-icon size="24"><Money /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">¥{{ formatNumber(analysisOverview.costSaved) }}</div>
              <div class="card-label">成本节约</div>
              <div class="card-trend down">
                <el-icon><Bottom /></el-icon>
                {{ analysisOverview.saveRate }}%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon cost-forecast">
              <el-icon size="24"><DataLine /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">¥{{ formatNumber(analysisOverview.forecastCost) }}</div>
              <div class="card-label">预测成本</div>
              <div class="card-trend up">
                <el-icon><Top /></el-icon>
                {{ analysisOverview.forecastGrowth }}%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 筛选区域 -->
    <el-card class="filter-card">
      <el-form :model="filterForm" inline>
        <el-form-item label="分析维度">
          <el-select v-model="filterForm.dimension" placeholder="请选择分析维度">
            <el-option label="按产品分析" value="product" />
            <el-option label="按类型分析" value="type" />
            <el-option label="按部门分析" value="department" />
            <el-option label="按时间分析" value="time" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="对比维度">
          <el-select v-model="filterForm.compareWith" placeholder="请选择对比维度">
            <el-option label="无对比" value="none" />
            <el-option label="同比" value="year" />
            <el-option label="环比" value="month" />
            <el-option label="自定义对比" value="custom" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAnalyze">
            <el-icon><DataAnalysis /></el-icon>
            开始分析
          </el-button>
          <el-button @click="handleExport">
            <el-icon><Download /></el-icon>
            导出报告
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 成本构成分析 -->
    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :xs="24" :md="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>成本构成分析</span>
              <el-tag type="info">饼图</el-tag>
            </div>
          </template>
          <div ref="costCompositionChart" style="width: 100%; height: 400px"></div>
        </el-card>
      </el-col>
      <el-col :xs="24" :md="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>成本趋势分析</span>
              <el-tag type="success">折线图</el-tag>
            </div>
          </template>
          <div ref="costTrendChart" style="width: 100%; height: 400px"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 成本对比分析 -->
    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :xs="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>产品成本对比分析</span>
              <el-tag type="warning">柱状图</el-tag>
            </div>
          </template>
          <div ref="costCompareChart" style="width: 100%; height: 400px"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 成本详细数据表 -->
    <el-card style="margin-top: 20px">
      <template #header>
        <div class="card-header">
          <span>成本明细数据</span>
          <div class="header-actions">
            <el-button size="small" @click="handleRefresh">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <el-table :data="costDetailData" v-loading="loading" stripe>
        <el-table-column prop="productName" label="产品名称" width="150" />
        <el-table-column prop="productCode" label="产品编码" width="120" />
        <el-table-column label="直接材料成本" width="130" align="right">
          <template #default="{ row }">
            <span class="cost-value">¥{{ formatNumber(row.materialCost) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="占比" width="80" align="right">
          <template #default="{ row }">
            {{ calculatePercentage(row.materialCost, row.totalCost) }}%
          </template>
        </el-table-column>
        <el-table-column label="直接人工成本" width="130" align="right">
          <template #default="{ row }">
            <span class="cost-value">¥{{ formatNumber(row.laborCost) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="占比" width="80" align="right">
          <template #default="{ row }">
            {{ calculatePercentage(row.laborCost, row.totalCost) }}%
          </template>
        </el-table-column>
        <el-table-column label="制造费用" width="120" align="right">
          <template #default="{ row }">
            <span class="cost-value">¥{{ formatNumber(row.overheadCost) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="占比" width="80" align="right">
          <template #default="{ row }">
            {{ calculatePercentage(row.overheadCost, row.totalCost) }}%
          </template>
        </el-table-column>
        <el-table-column label="总成本" width="130" align="right">
          <template #default="{ row }">
            <span class="total-cost-value">¥{{ formatNumber(row.totalCost) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="单位成本" width="120" align="right">
          <template #default="{ row }">
            <span class="unit-cost-value">¥{{ formatNumber(row.unitCost) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="环比" width="100">
          <template #default="{ row }">
            <span :class="row.monthChange >= 0 ? 'trend-up' : 'trend-down'">
              <el-icon>
                <component :is="row.monthChange >= 0 ? 'Top' : 'Bottom'" />
              </el-icon>
              {{ Math.abs(row.monthChange) }}%
            </span>
          </template>
        </el-table-column>
        <el-table-column label="同比" width="100">
          <template #default="{ row }">
            <span :class="row.yearChange >= 0 ? 'trend-up' : 'trend-down'">
              <el-icon>
                <component :is="row.yearChange >= 0 ? 'Top' : 'Bottom'" />
              </el-icon>
              {{ Math.abs(row.yearChange) }}%
            </span>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 成本优化建议 -->
    <el-card style="margin-top: 20px">
      <template #header>
        <div class="card-header">
          <span>成本优化建议</span>
          <el-tag type="danger">AI智能分析</el-tag>
        </div>
      </template>

      <el-timeline>
        <el-timeline-item
          v-for="(suggestion, index) in costSuggestions"
          :key="index"
          :timestamp="suggestion.time"
          placement="top"
          :type="suggestion.type"
        >
          <el-card>
            <h4>{{ suggestion.title }}</h4>
            <p>{{ suggestion.content }}</p>
            <div class="suggestion-tags">
              <el-tag 
                v-for="tag in suggestion.tags" 
                :key="tag" 
                size="small" 
                style="margin-right: 8px"
              >
                {{ tag }}
              </el-tag>
            </div>
            <div class="suggestion-footer">
              <span class="expected-save">预计节约：¥{{ formatNumber(suggestion.expectedSave) }}</span>
              <el-button type="primary" size="small">查看详情</el-button>
            </div>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'

// 响应式数据
const loading = ref(false)
const costCompositionChart = ref()
const costTrendChart = ref()
const costCompareChart = ref()

// 分析概览数据
const analysisOverview = reactive({
  currentMonthCost: 1250000,
  monthGrowth: 5.8,
  costRate: 68.5,
  rateChange: 2.3,
  costSaved: 85000,
  saveRate: 6.4,
  forecastCost: 1320000,
  forecastGrowth: 5.6
})

// 筛选表单
const filterForm = reactive({
  dimension: 'product',
  dateRange: [],
  compareWith: 'month'
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 成本详细数据
const costDetailData = ref([
  {
    productName: '智能手机X1',
    productCode: 'SP001',
    materialCost: 350000,
    laborCost: 120000,
    overheadCost: 80000,
    totalCost: 550000,
    unitCost: 550,
    monthChange: -3.5,
    yearChange: 2.8
  },
  {
    productName: '平板电脑T1',
    productCode: 'TB001',
    materialCost: 180000,
    laborCost: 60000,
    overheadCost: 40000,
    totalCost: 280000,
    unitCost: 560,
    monthChange: 4.2,
    yearChange: -1.5
  },
  {
    productName: '智能手表W1',
    productCode: 'SW001',
    materialCost: 200000,
    laborCost: 80000,
    overheadCost: 50000,
    totalCost: 330000,
    unitCost: 165,
    monthChange: -2.1,
    yearChange: 5.6
  },
  {
    productName: '无线耳机E1',
    productCode: 'EB001',
    materialCost: 90000,
    laborCost: 30000,
    overheadCost: 20000,
    totalCost: 140000,
    unitCost: 46.67,
    monthChange: 1.8,
    yearChange: -3.2
  }
])

// 成本优化建议
const costSuggestions = ref([
  {
    time: '2024-01-15 10:30',
    type: 'danger',
    title: '材料成本异常增长预警',
    content: '检测到智能手机X1的材料成本环比上涨12.5%，建议优化供应商采购策略，考虑批量采购降低单价。',
    tags: ['材料成本', '供应商优化', '批量采购'],
    expectedSave: 45000
  },
  {
    time: '2024-01-15 09:15',
    type: 'warning',
    title: '人工成本优化建议',
    content: '平板电脑T1的人工成本占比较高，建议引入自动化生产设备，提高生产效率，降低人工成本。',
    tags: ['人工成本', '自动化', '效率提升'],
    expectedSave: 28000
  },
  {
    time: '2024-01-14 16:45',
    type: 'success',
    title: '制造费用分摊优化',
    content: '通过优化制造费用分摊方法，可以更准确地反映各产品的真实成本，建议采用作业成本法进行精细化管理。',
    tags: ['制造费用', '成本分摊', '精细化管理'],
    expectedSave: 12000
  },
  {
    time: '2024-01-14 14:20',
    type: 'primary',
    title: '库存成本控制建议',
    content: '无线耳机E1的库存周转率较低，建议优化库存管理策略，采用JIT准时制生产，减少库存积压。',
    tags: ['库存管理', 'JIT', '周转率'],
    expectedSave: 18000
  }
])

// 方法
const formatNumber = (value) => {
  if (typeof value === 'number') {
    return value.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
  }
  return value
}

const calculatePercentage = (part, total) => {
  if (total === 0) return 0
  return ((part / total) * 100).toFixed(1)
}

const initCostCompositionChart = () => {
  const chart = echarts.init(costCompositionChart.value)
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: ¥{c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center'
    },
    series: [
      {
        name: '成本构成',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 20,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 820000, name: '直接材料成本', itemStyle: { color: '#5470c6' } },
          { value: 290000, name: '直接人工成本', itemStyle: { color: '#91cc75' } },
          { value: 190000, name: '制造费用', itemStyle: { color: '#fac858' } }
        ]
      }
    ]
  }
  chart.setOption(option)
  
  // 响应式调整
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

const initCostTrendChart = () => {
  const chart = echarts.init(costTrendChart.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['直接材料', '直接人工', '制造费用', '总成本'],
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '12%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '¥{value}'
      }
    },
    series: [
      {
        name: '直接材料',
        type: 'line',
        smooth: true,
        data: [680000, 720000, 750000, 780000, 800000, 820000, 810000, 830000, 850000, 870000, 860000, 880000],
        itemStyle: { color: '#5470c6' }
      },
      {
        name: '直接人工',
        type: 'line',
        smooth: true,
        data: [250000, 260000, 255000, 270000, 275000, 290000, 285000, 295000, 300000, 310000, 305000, 315000],
        itemStyle: { color: '#91cc75' }
      },
      {
        name: '制造费用',
        type: 'line',
        smooth: true,
        data: [160000, 165000, 170000, 172000, 175000, 190000, 185000, 192000, 195000, 198000, 200000, 205000],
        itemStyle: { color: '#fac858' }
      },
      {
        name: '总成本',
        type: 'line',
        smooth: true,
        lineStyle: {
          width: 3
        },
        data: [1090000, 1145000, 1175000, 1222000, 1250000, 1300000, 1280000, 1317000, 1345000, 1378000, 1365000, 1400000],
        itemStyle: { color: '#ee6666' }
      }
    ]
  }
  chart.setOption(option)
  
  // 响应式调整
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

const initCostCompareChart = () => {
  const chart = echarts.init(costCompareChart.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['直接材料成本', '直接人工成本', '制造费用'],
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '12%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['智能手机X1', '平板电脑T1', '智能手表W1', '无线耳机E1']
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '¥{value}'
      }
    },
    series: [
      {
        name: '直接材料成本',
        type: 'bar',
        stack: 'total',
        data: [350000, 180000, 200000, 90000],
        itemStyle: { color: '#5470c6' }
      },
      {
        name: '直接人工成本',
        type: 'bar',
        stack: 'total',
        data: [120000, 60000, 80000, 30000],
        itemStyle: { color: '#91cc75' }
      },
      {
        name: '制造费用',
        type: 'bar',
        stack: 'total',
        data: [80000, 40000, 50000, 20000],
        itemStyle: { color: '#fac858' }
      }
    ]
  }
  chart.setOption(option)
  
  // 响应式调整
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

const loadData = () => {
  loading.value = true
  setTimeout(() => {
    pagination.total = costDetailData.value.length
    loading.value = false
  }, 500)
}

const handleAnalyze = () => {
  ElMessage.success('分析完成')
  loadData()
}

const handleExport = () => {
  ElMessage.success('报告导出成功')
}

const handleRefresh = () => {
  loadData()
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadData()
}

// 生命周期
onMounted(() => {
  loadData()
  nextTick(() => {
    initCostCompositionChart()
    initCostTrendChart()
    initCostCompareChart()
  })
})
</script>

<style scoped>
.cost-analysis-page {
  padding: 0;
}

.overview-cards {
  margin-bottom: 20px;
}

.overview-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-content {
  display: flex;
  align-items: center;
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  color: white;
}

.card-icon.current-cost {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.card-icon.cost-rate {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.card-icon.cost-save {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.card-icon.cost-forecast {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.card-info {
  flex: 1;
}

.card-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.card-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 4px;
}

.card-trend {
  font-size: 12px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 4px;
}

.card-trend.up {
  color: #f56c6c;
}

.card-trend.down {
  color: #67c23a;
}

.filter-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.cost-value {
  color: #409eff;
  font-weight: 600;
}

.total-cost-value {
  color: #f56c6c;
  font-weight: 700;
}

.unit-cost-value {
  color: #67c23a;
  font-weight: 600;
}

.trend-up {
  color: #f56c6c;
  display: flex;
  align-items: center;
  gap: 4px;
}

.trend-down {
  color: #67c23a;
  display: flex;
  align-items: center;
  gap: 4px;
}

.suggestion-tags {
  margin: 12px 0;
}

.suggestion-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12px;
}

.expected-save {
  font-size: 14px;
  font-weight: 600;
  color: #67c23a;
}
</style>

